package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.pojo.dto.SpecGroupDTO;
import com.leyou.item.pojo.dto.SpecParamDTO;
import com.leyou.item.pojo.dto.SpuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class SpecGroupService {
    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SpecParamService specParamService;

    //根据分类id查询规格组信息
    public List<SpecGroupDTO> queryGroupByCategory(Long categoryId) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(categoryId);
        List<SpecGroup> record = specGroupMapper.select(specGroup);
        if (CollectionUtils.isEmpty(record)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(record, SpecGroupDTO.class);
    }

    //新增参数组
    @Transactional
    public void addParamGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = BeanHelper.copyProperties(specGroupDTO, SpecGroup.class);
        specGroupMapper.insertSelective(specGroup);
    }

    /**
     * 根据categoryId查询规格组以及对应的规格参数信息
     *
     * @param categoryId
     * @return
     */
    public List<SpecGroupDTO> querySpecsByCid(Long categoryId) {

        //根据分类id查询规格组信息
        List<SpecGroupDTO> specGroupDTOS = queryGroupByCategory(categoryId);

        //根据分类id查询所有规格参数信息
        List<SpecParamDTO> specParamDTOS = specParamService.querySpecParamsByGroupId(null,categoryId,null);

        //将所有的规格参数按照groupId进行分组
        Map<Long, List<SpecParamDTO>> specParamDTOMap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //根据规格组Id从 分好组的规格参数Map中取出对应的规格参数集合


        specGroupDTOS.stream().forEach(s->s.setParams(specParamDTOMap.get(s.getId())));

        //如果参数为空就舍弃这个规格组
        List<SpecGroupDTO> result = new ArrayList<>();
        for (SpecGroupDTO group : specGroupDTOS) {
            List<SpecParamDTO> params = group.getParams();
            if (!CollectionUtils.isEmpty(params)){
                result.add(group);
            }
        }

        return result;
    }


}
